package per.sunmes.cl.g.data;

import per.sunmes.cl.g.actor.Card;
import per.sunmes.cl.g.actor.Player;
import per.sunmes.cl.g.actor.Zone;
import per.sunmes.cl.g.i.Ai;
import per.sunmes.cl.g.i.CallAction;
import per.sunmes.cl.g.screen.GameScreen;
import per.sunmes.cl.g.sys.RandU;

import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.utils.Array;

public class SimpleEnemyAI implements Ai {
	GameScreen gameScreen;
	Player self;
	Zone[][] zoneMap;

	public SimpleEnemyAI(Player p, Zone[][] zoneMap, GameScreen gameScreen) {
		self = p;
		this.gameScreen = gameScreen;
		this.zoneMap = zoneMap;
	}

	Array<Zone> validZone = new Array<Zone>();

	@Override
	public void useCard() {
		if (!checkHandCards()) {
			return;
		}
		updateValidZone();
		if (validZone.size < 1) {
			return;
		}
		checkUseCard();
	}

	private boolean checkHandCards() {
		if (self.getHandCards().size < 1) {
			return false;
		}
		return true;
	}

	private void checkUseCard() {
		Zone targetZone = validZone.get(RandU.rand(0, validZone.size));
		Card card = self.getHandCards().get(
				RandU.rand(0, self.getHandCards().size));
		card.addAction(Actions.sequence(gameScreen.actionCardMoveToShowArea(),
				new CallAction() {
					public void call() {
						card.showFrontPage();
					}
				}, Actions.delay(0.3f), new CallAction() {
					public void call() {
						self.getHandCards().removeValue(card, true);
						gameScreen.resetPlayerHandCard(self);
						card.getCardData().getEffect()
								.effect(gameScreen, targetZone, card);
					}
				}));
	}

	private void updateValidZone() {
		validZone.clear();
		for (int y = 0; y < zoneMap[0].length; y++) {
			for (int x = 0; x < zoneMap.length; x++) {
				Zone zone = zoneMap[x][y];
				if (zone != null && zone.getCard() == null) {
					validZone.add(zone);
				}
			}
		}
	}

	@Override
	public void roundEnd() {
	}

}
